package com.zhangfb95.crosschain.plugin.container.java.fabric2.infra.extend.fabricsupport;

import com.zhangfb95.crosschain.infra.exception.BusinessException;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.security.CryptoSuiteFactory;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.Properties;

/**
 * @author zhangfubing
 * @since 2023/11/4
 */
@Component
public class StdCryptoSuite implements CryptoSuite {

    private final CryptoSuite cryptoSuite;

    public StdCryptoSuite() {
        try {
            this.cryptoSuite = Factory.getCryptoSuite();
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    @Override
    public CryptoSuiteFactory getCryptoSuiteFactory() {
        return cryptoSuite.getCryptoSuiteFactory();
    }

    @Override
    public Properties getProperties() {
        return cryptoSuite.getProperties();
    }

    @Override
    public void loadCACertificates(Collection<Certificate> certificates) throws CryptoException {
        cryptoSuite.loadCACertificates(certificates);
    }

    @Override
    public void loadCACertificatesAsBytes(Collection<byte[]> certificates) throws CryptoException {
        cryptoSuite.loadCACertificatesAsBytes(certificates);
    }

    @Override
    public KeyPair keyGen() throws CryptoException {
        return cryptoSuite.keyGen();
    }

    @Override
    public byte[] sign(PrivateKey key, byte[] plainText) throws CryptoException {
        return cryptoSuite.sign(key, plainText);
    }

    @Override
    public boolean verify(byte[] certificate,
                          String signatureAlgorithm,
                          byte[] signature,
                          byte[] plainText) throws CryptoException {
        return cryptoSuite.verify(certificate, signatureAlgorithm, signature, plainText);
    }

    @Override
    public byte[] hash(byte[] plainText) {
        return cryptoSuite.hash(plainText);
    }

    @Override
    public String generateCertificationRequest(String user, KeyPair keypair) throws InvalidArgumentException {
        return cryptoSuite.generateCertificationRequest(user, keypair);
    }

    @Override
    public Certificate bytesToCertificate(byte[] certBytes) throws CryptoException {
        return cryptoSuite.bytesToCertificate(certBytes);
    }
}
